{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  官网demo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.aliyun.com/pypi/simple\n",
      "Collecting pickleshare\n",
      "  Downloading https://mirrors.aliyun.com/pypi/packages/9a/41/220f49aaea88bc6fa6cba8d05ecf24676326156c23b991e80b3f2fc24c77/pickleshare-0.7.5-py2.py3-none-any.whl (6.9 kB)\n",
      "Installing collected packages: pickleshare\n",
      "Successfully installed pickleshare-0.7.5\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.0\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install pickleshare"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "current dir /home/wm\n",
      "change dir\n",
      "/home/wm/statebear/jupyter/tensorflow/demo\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'/home/wm/statebear/jupyter/tensorflow/demo'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " # 切换目录\n",
    "c_dir = %pwd\n",
    "print(\"current dir\",c_dir)\n",
    "if ('tensorflow' not in c_dir):\n",
    "    print(\"change dir\")\n",
    "    %cd statebear/jupyter/tensorflow/demo\n",
    "%pwd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-05-06 15:25:53.160435: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory\n",
      "2024-05-06 15:25:53.160478: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.\n",
      "/home/wm/py39_tf/lib/python3.9/site-packages/tensorflow_addons/utils/tfa_eol_msg.py:23: UserWarning: \n",
      "\n",
      "TensorFlow Addons (TFA) has ended development and introduction of new features.\n",
      "TFA has entered a minimal maintenance and release mode until a planned end of life in May 2024.\n",
      "Please modify downstream libraries to take dependencies from other repositories in our TensorFlow community (e.g. Keras, Keras-CV, and Keras-NLP). \n",
      "\n",
      "For more information see: https://github.com/tensorflow/addons/issues/2807 \n",
      "\n",
      "  warnings.warn(\n",
      "/home/wm/py39_tf/lib/python3.9/site-packages/tensorflow_addons/utils/ensure_tf_install.py:53: UserWarning: Tensorflow Addons supports using Python ops for all Tensorflow versions above or equal to 2.13.0 and strictly below 2.16.0 (nightly versions are not supported). \n",
      " The versions of TensorFlow you are currently using is 2.8.4 and is not supported. \n",
      "Some things might work, some things might not.\n",
      "If you were to encounter a bug, do not file an issue.\n",
      "If you want to make sure you're using a tested and supported configuration, either change the TensorFlow version or the TensorFlow Addons's version. \n",
      "You can find the compatibility matrix in TensorFlow Addon's readme:\n",
      "https://github.com/tensorflow/addons\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz\n",
      "228818944/228813984 [==============================] - 336s 1us/step\n",
      "228827136/228813984 [==============================] - 336s 1us/step\n",
      "INFO:tensorflow:Load image with size: 3670, num_label: 5, labels: daisy, dandelion, roses, sunflowers, tulips.\n",
      "INFO:tensorflow:Retraining the models...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-05-06 15:31:39.004010: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /home/wm/py39_tf/lib/python3.9/site-packages/cv2/../../lib64:\n",
      "2024-05-06 15:31:39.004088: W tensorflow/stream_executor/cuda/cuda_driver.cc:269] failed call to cuInit: UNKNOWN ERROR (303)\n",
      "2024-05-06 15:31:39.004111: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (DESKTOP-VETER3I): /proc/driver/nvidia/version does not exist\n",
      "2024-05-06 15:31:39.014346: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA\n",
      "To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " hub_keras_layer_v1v2 (HubKe  (None, 1280)             3413024   \n",
      " rasLayerV1V2)                                                   \n",
      "                                                                 \n",
      " dropout (Dropout)           (None, 1280)              0         \n",
      "                                                                 \n",
      " dense (Dense)               (None, 5)                 6405      \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 3,419,429\n",
      "Trainable params: 6,405\n",
      "Non-trainable params: 3,413,024\n",
      "_________________________________________________________________\n",
      "None\n",
      "Epoch 1/5\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-05-06 15:31:44.008898: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 19267584 exceeds 10% of free system memory.\n",
      "2024-05-06 15:31:44.157030: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 19267584 exceeds 10% of free system memory.\n",
      "2024-05-06 15:31:44.181499: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 51380224 exceeds 10% of free system memory.\n",
      "2024-05-06 15:31:44.215394: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 19267584 exceeds 10% of free system memory.\n",
      "2024-05-06 15:31:44.279136: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 19267584 exceeds 10% of free system memory.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "91/91 [==============================] - 68s 730ms/step - loss: 0.9085 - accuracy: 0.7411 - val_loss: 0.6741 - val_accuracy: 0.8719\n",
      "Epoch 2/5\n",
      "91/91 [==============================] - 73s 799ms/step - loss: 0.6645 - accuracy: 0.8887 - val_loss: 0.6442 - val_accuracy: 0.8910\n",
      "Epoch 3/5\n",
      "91/91 [==============================] - 69s 750ms/step - loss: 0.6296 - accuracy: 0.9121 - val_loss: 0.6325 - val_accuracy: 0.8937\n",
      "Epoch 4/5\n",
      "91/91 [==============================] - 65s 719ms/step - loss: 0.6064 - accuracy: 0.9231 - val_loss: 0.6207 - val_accuracy: 0.9101\n",
      "Epoch 5/5\n",
      "91/91 [==============================] - 66s 728ms/step - loss: 0.5918 - accuracy: 0.9255 - val_loss: 0.6142 - val_accuracy: 0.9183\n",
      "12/12 [==============================] - 8s 582ms/step - loss: 0.5772 - accuracy: 0.9455\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-05-06 15:37:38.372266: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: /tmp/tmppj2xxjal/assets\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: /tmp/tmppj2xxjal/assets\n",
      "2024-05-06 15:37:43.816029: I tensorflow/core/grappler/devices.cc:66] Number of eligible GPUs (core count >= 8, compute capability >= 0.0): 0\n",
      "2024-05-06 15:37:43.817398: I tensorflow/core/grappler/clusters/single_machine.cc:358] Starting new session\n",
      "2024-05-06 15:37:43.921841: I tensorflow/core/grappler/optimizers/meta_optimizer.cc:1164] Optimization results for grappler item: graph_to_optimize\n",
      "  function_optimizer: Graph size after: 913 nodes (656), 923 edges (664), time = 61.839ms.\n",
      "  function_optimizer: function_optimizer did nothing. time = 0.017ms.\n",
      "\n",
      "/home/wm/py39_tf/lib/python3.9/site-packages/tensorflow/lite/python/convert.py:746: UserWarning: Statistics for quantized inputs were expected, but not specified; continuing anyway.\n",
      "  warnings.warn(\"Statistics for quantized inputs were expected, but not \"\n",
      "2024-05-06 15:37:45.289862: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:357] Ignored output_format.\n",
      "2024-05-06 15:37:45.289925: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored drop_control_dependency.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Label file is inside the TFLite model with metadata.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "fully_quantize: 0, inference_type: 6, input_inference_type: 3, output_inference_type: 3\n",
      "INFO:tensorflow:Label file is inside the TFLite model with metadata.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Saving labels in /tmp/tmp1fwt0xvk/labels.txt\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Saving labels in /tmp/tmp1fwt0xvk/labels.txt\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:TensorFlow Lite model exported successfully: ./model.tflite\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:TensorFlow Lite model exported successfully: ./model.tflite\n"
     ]
    }
   ],
   "source": [
    "\n",
    "from tflite_model_maker import image_classifier\n",
    "from tflite_model_maker.image_classifier import DataLoader\n",
    "import tensorflow as tf\n",
    "import os\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "# Load input data specific to an on-device ML app.\n",
    "image_path = tf.keras.utils.get_file(\n",
    "      'flower_photos.tgz',\n",
    "      'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',\n",
    "      extract=True)\n",
    "image_path = os.path.join(os.path.dirname(image_path), 'flower_photos')\n",
    "data = DataLoader.from_folder(image_path)\n",
    "train_data, rest_data = data.split(0.8)\n",
    "validation_data, test_data = rest_data.split(0.5)\n",
    "\n",
    "# Customize the TensorFlow model.\n",
    "model = image_classifier.create(train_data,validation_data=validation_data)\n",
    "\n",
    "# Evaluate the model.\n",
    "loss, accuracy = model.evaluate(test_data)\n",
    "\n",
    "# Export to Tensorflow Lite model and label file in `export_dir`.\n",
    "model.export(export_dir='.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'model' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[1], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mmodel\u001b[49m\u001b[38;5;241m.\u001b[39mevaluate_tflite(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mmodel.tflite\u001b[39m\u001b[38;5;124m'\u001b[39m, test_data)\n",
      "\u001b[0;31mNameError\u001b[0m: name 'model' is not defined"
     ]
    }
   ],
   "source": [
    "model.evaluate_tflite('model.tflite', test_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/wm/.keras/datasets/flower_photos\n"
     ]
    }
   ],
   "source": [
    "print(image_path)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
